<!--工程员工管理 -->
<script setup lang="ts">
import {
  getPage,
  getForm,
  add,
  update,
  deletes,
  getSaleCustomerOptions,
} from "@/api/plan/planchargersheet";
import {
  PlanChargerSheetFormVO,
  PlanChargerSheetQuery,
} from "@/api/plan/planchargersheet/types";
import { ElMessage, ElMessageBox, ElForm } from "element-plus";

defineOptions({
  name: "Planchargersheet", //
  inheritAttrs: false,
});

const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);

const loading = ref(false);
const ids = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<PlanChargerSheetQuery>({
  pageNum: 1,
  pageSize: 10,
});

const updateTimeRange = ref("");
const pageist = ref<PlanChargerSheetFormVO[]>();

watch(updateTimeRange, (newVal) => {
  if (newVal) {
    queryParams.startUpdateTime = newVal[0];
    queryParams.endUpdateTime = newVal[1];
  }
});

const dialog = reactive({
  title: "",
  visible: false,
});

//默认值
const formData = reactive<PlanChargerSheetFormVO>({
  status: 1,
  remark: "",
});

const rules = reactive({
  shippingNo: [
    { required: true, message: "请输入 送货地址编号", trigger: "blur" },
  ],
  customerNo: [{ required: true, message: "请输入 客户编号", trigger: "blur" }],
});

/** 查询 */
function handleQuery() {
  loading.value = true;
  getPage(queryParams)
    .then(({ data }) => {
      pageist.value = data.list;
      console.log(pageist);
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/**
 * 重置查询
 */
function resetQuery() {
  queryFormRef.value.resetFields();
  updateTimeRange.value = "";
  queryParams.pageNum = 1;
  queryParams.startUpdateTime = undefined;
  queryParams.endUpdateTime = undefined;
  queryParams.keywords = undefined;
  handleQuery();
}

/** 行复选框选中  */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.saleItemId);
}

/**
 * 打开表单弹窗
 *
 * @param id ID
 */
async function openEditDialog(id?: number) {
  dialog.visible = true;
  if (id) {
    dialog.title = "修改信息";
    getForm(id).then(({ data }) => {
      Object.assign(formData, data);
      console.log(formData);
    });
  } else {
    dialog.title = "新增";
  }

  //加载下拉数据
  await loadSaleCustomerOptions();
}

/**  表单提交 */
function handleSubmit() {
  dataFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      loading.value = false;
      const id = formData.planChargerSheetId;
      if (id) {
        update(id, formData)
          .then(() => {
            ElMessage.success("修改成功");
            closeDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        add(formData)
          .then(() => {
            ElMessage.success("新增成功");
            closeDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭弹窗 */
function closeDialog() {
  dialog.visible = false;
  resetForm();
}

/**  重置 表单 */
function resetForm() {
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();

  formData.planChargerSheetId = undefined;
  formData.status = 1;
}

/** 删除  */
function handleDelete(id?: number) {
  const idStrs = [id || ids.value].join(",");
  if (!idStrs) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    deletes(idStrs).then(() => {
      ElMessage.success("删除成功");
      resetQuery();
    });
  });
}

let saleCustomerList = [];

/** 加载工程员工下拉数据源 */
async function loadSaleCustomerOptions() {
  getSaleCustomerOptions().then((response) => {
    saleCustomerList = response.data;
    console.log(saleCustomerList);
  });
}

/** 详情弹窗 */
const planchargersheetDetailDialog = reactive({
  title: "",
  visible: false,
});

const selectedPlanchargersheet = reactive({ pmoNo: "" }); // 当前选中的

function openPlanchargersheetDetailDialog(row: PlanChargerSheetFormVO) {
  planchargersheetDetailDialog.visible = true;
  planchargersheetDetailDialog.title = "【" + row.pmoNo + "】数据";

  selectedPlanchargersheet.pmoNo = row.pmoNo;
}

/**  关闭详情弹窗 */
function closePlanchargersheetDetailDialog() {
  planchargersheetDetailDialog.visible = false;
}

/** 启动执行  */
onMounted(() => {
  handleQuery();
});
</script>

<template>
  <div class="app-container">
    <!--查询条件 -->
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="name">
          <el-input
            v-model="queryParams.keywords"
            placeholder="地址编号/客户编号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item label="更新时间">
          <el-date-picker
            class="!w-[240px]"
            v-model="updateTimeRange"
            type="daterange"
            range-separator="~"
            start-placeholder="开始时间"
            end-placeholder="截止时间"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery()"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="resetQuery()"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <!--功能按钮 -->
      <template #header>
        <el-button
          v-hasPerm="['plan:planchargersheet:add']"
          type="success"
          @click="openEditDialog()"
          ><i-ep-plus />新增</el-button
        >
        <el-button
          v-hasPerm="['plan:planchargersheet:del']"
          type="danger"
          :disabled="ids.length === 0"
          @click="handleDelete()"
          ><i-ep-delete />删除</el-button
        >
      </template>

      <el-table
        v-loading="loading"
        highlight-current-row
        :data="pageist"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="po/mo单号" prop="pmoNo" width="120" />
        <el-table-column label="行号" prop="pmoLine" width="120" />

        <el-table-column label="po/mo的标识" prop="pmoMark" width="80" />
        <el-table-column label="版次" prop="rev" width="80" />
        <el-table-column label="po/mo货号" prop="pmoItemNo" width="80" />

        <el-table-column label="状态" align="center" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 1" type="success">启用</el-tag>
            <el-tag v-else type="info">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remark" align="center" />
        <el-table-column label="更新者" prop="updateName" align="center" />
        <el-table-column
          label="更新时间"
          prop="updateTime"
          align="center"
          width="160"
        />
        <el-table-column fixed="right" label="操作" align="center" width="160">
          <template #default="scope">
            <el-button
              type="primary"
              link
              size="small"
              @click.stop="openPlanchargersheetDetailDialog(scope.row)"
              ><i-ep-Collection />订单明细</el-button
            >

            <el-button
              v-hasPerm="['plan:planchargersheet:edit']"
              type="primary"
              link
              size="small"
              @click.stop="openEditDialog(scope.row.planChargerSheetId)"
              ><i-ep-edit />编辑</el-button
            >
            <el-button
              v-hasPerm="['plan:planchargersheet:del']"
              type="primary"
              link
              size="small"
              @click.stop="handleDelete(scope.row.planChargerSheetId)"
              ><i-ep-delete />删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <!-- 弹出窗口 form -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="500px"
      @close="closeDialog"
    >
      <el-form
        ref="dataFormRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="po/mo单号" prop="pmoNo">
          <el-input v-model="formData.pmoNo" placeholder="请输入 单号" />
        </el-form-item>

        <el-form-item label="行号" prop="pmoLine">
          <el-input v-model="formData.pmoLine" placeholder="请输入 " />
        </el-form-item>
        <el-form-item label="po/mo的标识" prop="pmoMark">
          <el-input v-model="formData.pmoMark" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="版次" prop="rev">
          <el-input v-model="formData.rev" placeholder="请输入 " />
        </el-form-item>
        <el-form-item label="po/mo货号" prop="pmoItemNo">
          <el-input v-model="formData.pmoItemNo" placeholder="请输入 " />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            placeholder="请输入 备注"
            :autosize="{ minRows: 2, maxRows: 4 }"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!--配方详情弹窗-->
    <el-dialog
      v-model="planchargersheetDetailDialog.visible"
      :title="planchargersheetDetailDialog.title"
      width="1000px"
      @close="closePlanchargersheetDetailDialog"
    >
      <planchargersheet-detail v-model:pmoNo="selectedPlanchargersheet.pmoNo" />
    </el-dialog>
  </div>
</template>
